import styles from './index.module.scss'
import ArticleItem from '../ActicleItem'
import { useEffect, useState } from 'react'
// import request from '@/utils/request'
import { useDispatch } from 'react-redux'
import { getArticlesLsit } from '@/store/actions/home'
import { useSelector } from 'react-redux'
import { PullToRefresh, InfiniteScroll } from 'antd-mobile-v5'
/**
 * 文章列表组件
 * @param {String} props.channelId 当前文章列表所对应的频道ID
 * @param {String} props.aid 当前 Tab 栏选中的频道ID
 */
const ArticleList = ({ channelId, activeId }) => {
  const dispatch = useDispatch()
  const current = useSelector((state) => state.home.articles[channelId])
  useEffect(() => {
    // 如果该频道有文章数据，没必要一进来就发送请求
    if (current) return
    if (channelId === activeId) {
      dispatch(getArticlesLsit(channelId, Date.now()))
    }
  }, [channelId, activeId, dispatch, current])
  const onRefresh = async () => {
    // 下拉刷新，需要重新加载最新的数据
    setHasMore(true)
    await dispatch(getArticlesLsit(channelId, Date.now()))
  }
  // 是否有更多数据
  const [hasMore, setHasMore] = useState(true)
  // 代表是否正在加载数据
  const [loading, setLoading] = useState(false)
  const loadMore = async () => {
    // console.log('需要加载更多数据')
    // setHasMore(false)
    if (loading) return

    // 如果没有更多数据，不需要发送请求
    if (!current.timestamp) {
      setHasMore(false)
      return
    }

    setLoading(true)
    try {
      await dispatch(getArticlesLsit(channelId, current.timestamp, true))
    } finally {
      setLoading(false)
    }
  }
  // 如果不是当前频道，没有文章数据，先不渲染
  if (!current) return null

  return (
    <div className={styles.root}>
      <div className="articles">
        <PullToRefresh onRefresh={onRefresh}>
          {current.list.map((item) => (
            <div className="article-item" key={item.art_id}>
              <ArticleItem article={item}></ArticleItem>
            </div>
          ))}
        </PullToRefresh>
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
      </div>
    </div>
  )
}

export default ArticleList
